<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>MYSQL数据库事务和索引学习 | Yeding's Blog</title><meta name="keywords" content="Hexo，博文"><meta name="author" content="叶町"><meta name="copyright" content="叶町"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="数据库学习笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="MYSQL数据库事务和索引学习">
<meta property="og:url" content="https://www.yeding.top/post/f3d732a55ffc/index.html">
<meta property="og:site_name" content="Yeding&#39;s Blog">
<meta property="og:description" content="数据库学习笔记">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/5f6763fd160a154a6709d5e6.jpg">
<meta property="article:published_time" content="2020-09-20T06:21:22.000Z">
<meta property="article:modified_time" content="2020-10-04T23:46:52.000Z">
<meta property="article:author" content="叶町">
<meta property="article:tag" content="MYSQL">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/5f6763fd160a154a6709d5e6.jpg"><link rel="shortcut icon" href="/img/webicon.jpg"><link rel="canonical" href="https://www.yeding.top/post/f3d732a55ffc/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="msvalidate.01" content="278990AE0B56A7C826F87D7039A44A00"/><meta name="baidu-site-verification" content="code-c3G2TgtwfW"/><meta name="google-site-verification" content="_ae3149Ou1MfIkiKfOmwwj3AqiMp6ahEt9MT8YTVmtY"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isAnchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'MYSQL数据库事务和索引学习',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2020-10-05 07:46:52'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://testingcf.jsdelivr.net/gh/Lost-Swords/ImageLibrary/css/index.min.css"><link rel="stylesheet" href="//at.alicdn.com/t/font_2829204_gazvsq5039v.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Yeding's Blog" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "/image/loading.gif" data-lazy-src="https://s1.ax1x.com/2020/09/13/w0t8qe.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">10</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">12</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">4</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/5f6763fd160a154a6709d5e6.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Yeding's Blog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">MYSQL数据库事务和索引学习</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-09-20T06:21:22.000Z" title="发表于 2020-09-20 14:21:22">2020-09-20</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2020-10-04T23:46:52.000Z" title="更新于 2020-10-05 07:46:52">2020-10-05</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF/">技术</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.6k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>11分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="1事务"><a class="markdownIt-Anchor" href="#1事务"></a> 1.事务</h1>
<h2 id="11什么是事务"><a class="markdownIt-Anchor" href="#11什么是事务"></a> 1.1什么是事务</h2>
<p>事务是逻辑上的一组操作，要么都执行，要么都不执行。</p>
<ul>
<li>一个最小的不可再分的工作单元；通常一个事务对应一个完整的业务(例如银行账户转账业务，该业务就是一个最小的工作单元)</li>
</ul>
<h2 id="12事务的特征acid"><a class="markdownIt-Anchor" href="#12事务的特征acid"></a> 1.2事务的特征（ACID）</h2>
<ul>
<li>
<p>原子性(A)：事务是最小单位，不可再分</p>
</li>
<li>
<p>一致性©：事务要求所有的DML语句操作的时候，必须保证同时成功或者同时失败</p>
</li>
<li>
<p>隔离性(I)：事务A和事务B之间具有隔离性</p>
</li>
<li>
<p>持久性(D)：是事务的保证，事务终结的标志(内存的数据持久到硬盘文件中)</p>
</li>
</ul>
<h2 id="13并发运行事务带来的问题"><a class="markdownIt-Anchor" href="#13并发运行事务带来的问题"></a> 1.3并发运行事务带来的问题</h2>
<ul>
<li><strong>脏读（Dirty read）:</strong> 当一个事务正在访问数据并且对数据进行了修改，而这种修改还没有提交到数据库中，这时另外一个事务也访问了这个数据，然后使用了这个数据。因为这个数据是还没有提交的数据，那么另外一个事务读到的这个数据是“脏数据”，依据“脏数据”所做的操作可能是不正确的。</li>
<li><strong>丢失修改（Lost to modify）:</strong> 指在一个事务读取一个数据时，另外一个事务也访问了该数据，那么在第一个事务中修改了这个数据后，第二个事务也修改了这个数据。这样第一个事务内的修改结果就被丢失，因此称为丢失修改。 例如：事务1读取某表中的数据A=20，事务2也读取A=20，事务1修改A=A-1，事务2也修改A=A-1，最终结果A=19，事务1的修改被丢失。</li>
<li><strong>不可重复读（Unrepeatableread）:</strong> 指在一个事务内多次读同一数据。在这个事务还没有结束时，另一个事务也访问该数据。那么，在第一个事务中的两次读数据之间，由于第二个事务的修改导致第一个事务两次读取的数据可能不太一样。这就发生了在一个事务内两次读到的数据是不一样的情况，因此称为不可重复读。</li>
<li><strong>幻读（Phantom read）:</strong> 幻读与不可重复读类似。它发生在一个事务（T1）读取了几行数据，接着另一个并发事务（T2）插入了一些数据时。在随后的查询中，第一个事务（T1）就会发现多了一些原本不存在的记录，就好像发生了幻觉一样，所以称为幻读。</li>
</ul>
<p><strong>不可重复度和幻读区别：</strong></p>
<p>不可重复读的重点是修改，幻读的重点在于新增或者删除。</p>
<p>例1（同样的条件, 你读取过的数据, 再次读取出来发现值不一样了 ）：事务1中的A先生读取自己的工资为 1000的操作还没完成，事务2中的B先生就修改了A的工资为2000，导 致A再读自己的工资时工资变为 2000；这就是不可重复读。</p>
<p>例2（同样的条件, 第1次和第2次读出来的记录数不一样 ）：假某工资单表中工资大于3000的有4人，事务1读取了所有工资大于3000的人，共查到4条记录，这时事务2 又插入了一条工资大于3000的记录，事务1再次读取时查到的记录就变为了5条，这样就导致了幻读。</p>
<h2 id="14事务隔离级别"><a class="markdownIt-Anchor" href="#14事务隔离级别"></a> 1.4事务隔离级别</h2>
<p><strong>SQL 标准定义了四个隔离级别：</strong></p>
<ul>
<li><strong>READ-UNCOMMITTED(读取未提交)：</strong> 最低的隔离级别，允许读取尚未提交的数据变更，<strong>可能会导致脏读、幻读或不可重复读</strong>。<strong>可以防止丢失更新</strong></li>
<li><strong>READ-COMMITTED(读取已提交)：</strong> 允许读取并发事务已经提交的数据，<strong>可以阻止脏读，但是幻读或不可重复读仍有可能发生</strong>。</li>
<li><strong>REPEATABLE-READ(可重复读)：</strong> 对同一字段的多次读取结果都是一致的，除非数据是被本身事务自己所修改，<strong>可以阻止脏读和不可重复读，但幻读仍有可能发生</strong>。</li>
<li><strong>SERIALIZABLE(可串行化)：</strong> 最高的隔离级别，完全服从ACID的隔离级别。所有的事务依次逐个执行，这样事务之间就完全不可能产生干扰，也就是说，<strong>该级别可以防止脏读、不可重复读以及幻读</strong>。</li>
</ul>
<h2 id="15常用句式"><a class="markdownIt-Anchor" href="#15常用句式"></a> 1.5常用句式</h2>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">SET autocommit = 0 -- 关闭自动提交</span><br><span class="line"></span><br><span class="line">-- 事务开启</span><br><span class="line">START TRANSACTION -- 标记一个事务的开始，从这个以后的sql都在一个事务内</span><br><span class="line"></span><br><span class="line">INSERT XX</span><br><span class="line">UPDATE XX</span><br><span class="line">DELETE XX</span><br><span class="line"></span><br><span class="line">-- 提交：持久化（成功！）</span><br><span class="line">COMMIT</span><br><span class="line">-- 回滚：回到原来的样子（失败！）</span><br><span class="line">ROLLBACK</span><br><span class="line">-- 事务结束</span><br><span class="line">SET autocommit = 1 -- 开启自动提交</span><br><span class="line"></span><br><span class="line">-- 了解</span><br><span class="line">SAVEPOINT 保存点名 -- 设置一个事务的保存点</span><br><span class="line">ROLLBACK TO SAVEPOINT 保存点名 -- 回滚到保存点</span><br><span class="line">RELEASE SAVEPOINT 保存点名 -- 撤销保存点</span><br></pre></td></tr></table></figure>
<h2 id="16事务测试"><a class="markdownIt-Anchor" href="#16事务测试"></a> 1.6事务测试</h2>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">-- 转账</span><br><span class="line">CREATE DATABASE shop CHARACTER SET utf8 COLLATE utf8_general_ci</span><br><span class="line">USE shop</span><br><span class="line"></span><br><span class="line">CREATE TABLE account(</span><br><span class="line"> id INT(3) NOT NULL AUTO_INCREMENT,</span><br><span class="line"> name VARCHAR(30) NOT NULL,</span><br><span class="line"> money DECIMAL(9,2) NOT NULL,</span><br><span class="line"> PRIMARY KEY (id)</span><br><span class="line"> )ENGINE=INNODB DEFAULT CHARSET=utf8</span><br><span class="line"> </span><br><span class="line"> INSERT INTO account (`name`,`money`)</span><br><span class="line"> VALUES (&#x27;A&#x27;,2000.00),(&#x27;B&#x27;,10000.0)</span><br><span class="line"> </span><br><span class="line"> -- 模拟转账：事务</span><br><span class="line"> SET autocommit = 0; -- 关闭自动提交</span><br><span class="line"> START TRANSACTION -- 开启一个事务（一组事务）</span><br><span class="line"> </span><br><span class="line"> UPDATE account SET money=money-500 where `name` = &#x27;A&#x27;; -- A减500</span><br><span class="line"> UPDATE account SET money=money+500 where `name` = &#x27;B&#x27;</span><br><span class="line"> -- B加500</span><br><span class="line"> COMMIT; -- 提交事务，持久化</span><br><span class="line"> ROLLBACK;</span><br><span class="line"> </span><br><span class="line"> SET autocommit = 1；</span><br><span class="line"> </span><br></pre></td></tr></table></figure>
<h1 id="2索引"><a class="markdownIt-Anchor" href="#2索引"></a> 2.索引</h1>
<h2 id="21什么是索引"><a class="markdownIt-Anchor" href="#21什么是索引"></a> 2.1什么是索引</h2>
<p><strong>索引是一种用于快速查询和检索数据的数据结构。常见的索引结构有: B树， B+树和Hash。</strong></p>
<h2 id="22为什么使用索引"><a class="markdownIt-Anchor" href="#22为什么使用索引"></a> 2.2为什么使用索引</h2>
<p><strong>索引优化是对查询性能优化的最有效手段</strong>，它能够轻松地将查询的性能提高几个数量级。</p>
<h2 id="23索引的数据结构"><a class="markdownIt-Anchor" href="#23索引的数据结构"></a> 2.3索引的数据结构</h2>
<blockquote>
<p>b-tree</p>
</blockquote>
<p>一棵m阶的B-Tree有如下特性：</p>
<ol>
<li>每个节点最多有m个孩子。</li>
<li>除了根节点和叶子节点外，其它每个节点至少有Ceil(m/2)个孩子。</li>
<li>若根节点不是叶子节点，则至少有2个孩子</li>
<li>所有叶子节点都在同一层，且不包含其它关键字信息</li>
<li>每个非终端节点包含n个关键字信息（P0,P1,…Pn, k1,…kn）</li>
<li>关键字的个数n满足：ceil(m/2)-1 &lt;= n &lt;= m-1  ki(i=1,…n)为关键字，且关键字升序排序。</li>
<li>Pi(i=1,…n)为指向子树根节点的指针。P(i-1)指向的子树的所有节点关键字均小于ki，但都大于k(i-1)</li>
</ol>
<p><img src= "/image/loading.gif" data-lazy-src="https://image.yeding.top/img/b-tree.jpg" alt="b-树" /></p>
<blockquote>
<p>b+tree</p>
</blockquote>
<p>与b-tree的不同</p>
<ol>
<li>非叶子节点只存储键值信息。</li>
<li>所有叶子节点之间都有一个链指针。</li>
<li>数据记录都存放在叶子节点中。</li>
</ol>
<p><img src= "/image/loading.gif" data-lazy-src="https://image.yeding.top/img/b+tree.jpg" alt="b+树" title="索引" /></p>
<blockquote>
<p>hash表</p>
</blockquote>
<p>Hash索引指的就是Hash表，最大的优点就是能够在很短的时间内，根据Hash函数定位到数据所在的位置，这是B+树所不能比的。 <strong>B+ 树索引并不能找到一个给定键对应的具体值，它只能找到数据行对应的页</strong></p>
<h2 id="24-索引类型"><a class="markdownIt-Anchor" href="#24-索引类型"></a> 2.4 索引类型</h2>
<blockquote>
<p>主键索引(Primary Key)</p>
</blockquote>
<p><strong>数据表的主键列使用的就是主键索引。</strong></p>
<p>一张数据表有只能有一个主键，并且主键不能为null，不能重复。</p>
<p>在mysql的InnoDB的表中，当没有显示的指定表的主键时，InnoDB会自动先检查表中是否有唯一索引的字段，如果有，则选择该字段为默认的主键，否则InnoDB将会自动创建一个6Byte的自增主键。</p>
<blockquote>
<p>二级索引(辅助索引)</p>
</blockquote>
<p><strong>二级索引又称为辅助索引，是因为二级索引的叶子节点存储的数据是主键。也就是说，通过二级索引，可以定位主键的位置。</strong></p>
<p>唯一索引，普通索引，前缀索引等索引属于二级索引。</p>
<ol>
<li><strong>唯一索引(Unique Key)</strong> ：唯一索引也是一种约束。**唯一索引的属性列不能出现重复的数据，但是允许数据为NULL，一张表允许创建多个唯一索引。**建立唯一索引的目的大部分时候都是为了该属性列的数据的唯一性，而不是为了查询效率。</li>
<li><strong>普通索引(Index)</strong> ：<strong>普通索引的唯一作用就是为了快速查询数据，一张表允许创建多个普通索引，并允许数据重复和NULL。</strong></li>
<li><strong>前缀索引(Prefix)</strong> ：前缀索引只适用于字符串类型的数据。前缀索引是对文本的前几个字符创建索引，相比普通索引建立的数据更小， 因为只取前几个字符。</li>
<li><strong>全文索引(Full Text)</strong> ：全文索引主要是为了检索大文本数据中的关键字的信息，是目前搜索引擎数据库使用的一种技术。Mysql5.6之前只有MYISAM引擎支持全文索引，5.6之后InnoDB也支持了全文索引。</li>
</ol>
<p>二级索引: <img src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/5f67652b160a154a670a5295.png" alt="" /></p>
<h2 id="25聚集索引与非聚集索引"><a class="markdownIt-Anchor" href="#25聚集索引与非聚集索引"></a> 2.5聚集索引与非聚集索引</h2>
<h3 id="聚集索引"><a class="markdownIt-Anchor" href="#聚集索引"></a> 聚集索引</h3>
<p><strong>聚集索引即索引结构和数据一起存放的索引。主键索引属于聚集索引。</strong></p>
<p>在 Mysql 中，InnoDB引擎的表的 <code>.ibd</code>文件就包含了该表的索引和数据，对于 InnoDB 引擎表来说，该表的索引(B+树)的每个非叶子节点存储索引，叶子节点存储索引和索引对应的数据。</p>
<h4 id="聚集索引的优点"><a class="markdownIt-Anchor" href="#聚集索引的优点"></a> 聚集索引的优点</h4>
<p>聚集索引的查询速度非常的快，因为整个B+树本身就是一颗多叉平衡树，叶子节点也都是有序的，定位到索引的节点，就相当于定位到了数据。</p>
<h4 id="聚集索引的缺点"><a class="markdownIt-Anchor" href="#聚集索引的缺点"></a> 聚集索引的缺点</h4>
<ol>
<li><strong>依赖于有序的数据</strong> ：因为B+树是多路平衡树，如果索引的数据不是有序的，那么就需要在插入时排序，如果数据是整型还好，否则类似于字符串或UUID这种又长又难比较的数据，插入或查找的速度肯定比较慢。</li>
<li><strong>更新代价大</strong> ： 如果对索引列的数据被修改时，那么对应的索引也将会被修改， 而且况聚集索引的叶子节点还存放着数据，修改代价肯定是较大的， 所以对于主键索引来说，主键一般都是不可被修改的。</li>
</ol>
<h3 id="非聚集索引"><a class="markdownIt-Anchor" href="#非聚集索引"></a> 非聚集索引</h3>
<p><strong>非聚集索引即索引结构和数据分开存放的索引。</strong></p>
<p><strong>二级索引属于非聚集索引。</strong></p>
<blockquote>
<p>MYISAM引擎的表的.MYI文件包含了表的索引， 该表的索引(B+树)的每个叶子非叶子节点存储索引， 叶子节点存储索引和索引对应数据的指针，指向.MYD文件的数据。</p>
</blockquote>
<p><strong>非聚集索引的叶子节点并不一定存放数据的指针， 因为二级索引的叶子节点就存放的是主键，根据主键再回表查数据。</strong></p>
<h4 id="非聚集索引的优点"><a class="markdownIt-Anchor" href="#非聚集索引的优点"></a> 非聚集索引的优点</h4>
<p><strong>更新代价比聚集索引要小</strong> 。非聚集索引的更新代价就没有聚集索引那么大了，非聚集索引的叶子节点是不存放数据的</p>
<h4 id="非聚集索引的缺点"><a class="markdownIt-Anchor" href="#非聚集索引的缺点"></a> 非聚集索引的缺点</h4>
<ol>
<li>跟聚集索引一样，非聚集索引也依赖于有序的数据</li>
<li><strong>可能会二次查询(回表)</strong> :这应该是非聚集索引最大的缺点了。 当查到索引对应的指针或主键后，可能还需要根据指针或主键再到数据文件或表中查询。</li>
</ol>
<p>这是Mysql的表的文件截图:</p>
<p><img src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/Mysql%E7%B4%A2%E5%BC%95%E6%96%87%E4%BB%B6%E6%88%AA%E5%9B%BE.png" alt="Mysql表文件截图" /></p>
<p>聚集索引和非聚集索引:</p>
<p><img src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/B+%E6%A0%91%E7%B4%A2%E5%BC%95.png" alt="聚集索引" /></p>
<h3 id="覆盖索引"><a class="markdownIt-Anchor" href="#覆盖索引"></a> 覆盖索引</h3>
<p>如果一个索引包含（或者说覆盖）所有需要查询的字段的值，我们就称之为“覆盖索引”。我们知道在InnoDB存储引擎中，如果不是主键索引，叶子节点存储的是主键+列值。最终还是要“回表”，也就是要通过主键再查找一次。这样就会比较慢覆盖索引就是把要查询出的列和索引是对应的，不做回表操作！</p>
<p><strong>覆盖索引即需要查询的字段正好是索引的字段，那么直接根据该索引，就可以查到数据了， 而无需回表查询。</strong></p>
<blockquote>
<p>如主键索引，如果一条SQL需要查询主键，那么正好根据主键索引就可以查到主键。</p>
<p>再如普通索引，如果一条SQL需要查询name，name字段正好有索引， 那么直接根据这个索引就可以查到数据，也无需回表。</p>
</blockquote>
<p>覆盖索引: <img src= "/image/loading.gif" data-lazy-src="https://image.yeding.top/img/20210420165341868.png" alt="覆盖索引" /></p>
<h2 id="26最左前缀原则"><a class="markdownIt-Anchor" href="#26最左前缀原则"></a> 2.6最左前缀原则</h2>
<p>MySQL中的索引可以以一定顺序引用多列，这种索引叫作联合索引。如User表的name和city加联合索引就是(name,city)，而最左前缀原则指的是，如果查询的时候查询条件精确匹配索引的左边连续一列或几列，则此列就可以被用到。如下：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> <span class="keyword">user</span> <span class="keyword">where</span> name<span class="operator">=</span>xx <span class="keyword">and</span> city<span class="operator">=</span>xx ; ／／可以命中索引</span><br><span class="line"><span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> <span class="keyword">user</span> <span class="keyword">where</span> name<span class="operator">=</span>xx ; <span class="operator">/</span><span class="operator">/</span> 可以命中索引</span><br><span class="line"><span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> <span class="keyword">user</span> <span class="keyword">where</span> city<span class="operator">=</span>xx ; <span class="operator">/</span><span class="operator">/</span> 无法命中索引            <span class="keyword">Copy</span> <span class="keyword">to</span> clipboardErrorCopied</span><br></pre></td></tr></table></figure>
<p>这里需要注意的是，查询的时候如果两个条件都用上了，但是顺序不同，如 <code>city= xx and name ＝xx</code>，那么现在的查询引擎会自动优化为匹配联合索引的顺序，这样是能够命中索引的。</p>
<p>由于最左前缀原则，在创建联合索引时，索引字段的顺序需要考虑字段值去重之后的个数，较多的放前面。ORDER BY子句也遵循此规则。</p>
<h2 id="27如何为表字段添加索引"><a class="markdownIt-Anchor" href="#27如何为表字段添加索引"></a> 2.7如何为表字段添加索引</h2>
<p>1.添加PRIMARY KEY（主键索引）</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> `table_name` <span class="keyword">ADD</span> <span class="keyword">PRIMARY</span> KEY ( `<span class="keyword">column</span>` ) <span class="keyword">Copy</span> <span class="keyword">to</span> clipboardErrorCopied</span><br></pre></td></tr></table></figure>
<p>2.添加UNIQUE(唯一索引)</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> `table_name` <span class="keyword">ADD</span> <span class="keyword">UNIQUE</span> ( `<span class="keyword">column</span>` ) <span class="keyword">Copy</span> <span class="keyword">to</span> clipboardErrorCopied</span><br></pre></td></tr></table></figure>
<p>3.添加INDEX(普通索引)</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> `table_name` <span class="keyword">ADD</span> INDEX index_name ( `<span class="keyword">column</span>` )<span class="keyword">Copy</span> <span class="keyword">to</span> clipboardErrorCopied</span><br></pre></td></tr></table></figure>
<p>4.添加FULLTEXT(全文索引)</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> `table_name` <span class="keyword">ADD</span> FULLTEXT ( `<span class="keyword">column</span>`) <span class="keyword">Copy</span> <span class="keyword">to</span> clipboardErrorCopied</span><br></pre></td></tr></table></figure>
<p>5.添加多列索引</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> `table_name` <span class="keyword">ADD</span> INDEX index_name ( `column1`, `column2`, `column3` )</span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://www.yeding.top">叶町</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://www.yeding.top/post/f3d732a55ffc/">https://www.yeding.top/post/f3d732a55ffc/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://www.yeding.top" target="_blank">Yeding's Blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/MYSQL/">MYSQL</a></div><div class="post_share"><div class="social-share" data-image="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/5f6763fd160a154a6709d5e6.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/gh/overtrue/share.js@master/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/post/dde04d069e3b/"><img class="prev-cover" src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/89478039_p0.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">JVM入门笔记</div></div></a></div><div class="next-post pull-right"><a href="/post/08fb3a6a9e16/"><img class="next-cover" src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/5f6496f6160a154a674aaf48.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Java多线程学习笔记</div></div></a></div></nav><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "/image/loading.gif" data-lazy-src="https://s1.ax1x.com/2020/09/13/w0t8qe.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">叶町</div><div class="author-info__description">不要去了解我，也不要用因果报应咒骂我</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">10</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">12</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">4</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://space.bilibili.com/3169866"><i class="iconfont icon-bilibili-line"></i><span>关注我的B站账号</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://testingcf.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/weixinCode.jpg" target="_blank" title="微信"><i class="fab fa-weixin"></i></a><a class="social-icon" href="tencent://message/?uin=502818113&amp;Site=yedingBlog&amp;Menu=yes" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="https://github.com/Lost-Swords" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:kanaumachi@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title=""><i class="fas fa-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content"><div class="social-button"> <a style="display:block;margin:.2rem 0;background-color:var(--btn-bg);color:var(--btn-color);text-align:center;line-height:2.4;;transition:all .3s;position:relative;z-index:1;" class="button--animated" href="https://yeding708.lofter.com/" rel="external nofollow noreferrer" target="_blank"><i class="iconfont icon-lofter"></i><span>关注我的LOFTER</span></a> </div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#1%E4%BA%8B%E5%8A%A1"><span class="toc-text"> 1.事务</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#11%E4%BB%80%E4%B9%88%E6%98%AF%E4%BA%8B%E5%8A%A1"><span class="toc-text"> 1.1什么是事务</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#12%E4%BA%8B%E5%8A%A1%E7%9A%84%E7%89%B9%E5%BE%81acid"><span class="toc-text"> 1.2事务的特征（ACID）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#13%E5%B9%B6%E5%8F%91%E8%BF%90%E8%A1%8C%E4%BA%8B%E5%8A%A1%E5%B8%A6%E6%9D%A5%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-text"> 1.3并发运行事务带来的问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#14%E4%BA%8B%E5%8A%A1%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB"><span class="toc-text"> 1.4事务隔离级别</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#15%E5%B8%B8%E7%94%A8%E5%8F%A5%E5%BC%8F"><span class="toc-text"> 1.5常用句式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#16%E4%BA%8B%E5%8A%A1%E6%B5%8B%E8%AF%95"><span class="toc-text"> 1.6事务测试</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#2%E7%B4%A2%E5%BC%95"><span class="toc-text"> 2.索引</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#21%E4%BB%80%E4%B9%88%E6%98%AF%E7%B4%A2%E5%BC%95"><span class="toc-text"> 2.1什么是索引</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#22%E4%B8%BA%E4%BB%80%E4%B9%88%E4%BD%BF%E7%94%A8%E7%B4%A2%E5%BC%95"><span class="toc-text"> 2.2为什么使用索引</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#23%E7%B4%A2%E5%BC%95%E7%9A%84%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84"><span class="toc-text"> 2.3索引的数据结构</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#24-%E7%B4%A2%E5%BC%95%E7%B1%BB%E5%9E%8B"><span class="toc-text"> 2.4 索引类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#25%E8%81%9A%E9%9B%86%E7%B4%A2%E5%BC%95%E4%B8%8E%E9%9D%9E%E8%81%9A%E9%9B%86%E7%B4%A2%E5%BC%95"><span class="toc-text"> 2.5聚集索引与非聚集索引</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%81%9A%E9%9B%86%E7%B4%A2%E5%BC%95"><span class="toc-text"> 聚集索引</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%81%9A%E9%9B%86%E7%B4%A2%E5%BC%95%E7%9A%84%E4%BC%98%E7%82%B9"><span class="toc-text"> 聚集索引的优点</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%81%9A%E9%9B%86%E7%B4%A2%E5%BC%95%E7%9A%84%E7%BC%BA%E7%82%B9"><span class="toc-text"> 聚集索引的缺点</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9D%9E%E8%81%9A%E9%9B%86%E7%B4%A2%E5%BC%95"><span class="toc-text"> 非聚集索引</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%9D%9E%E8%81%9A%E9%9B%86%E7%B4%A2%E5%BC%95%E7%9A%84%E4%BC%98%E7%82%B9"><span class="toc-text"> 非聚集索引的优点</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%9D%9E%E8%81%9A%E9%9B%86%E7%B4%A2%E5%BC%95%E7%9A%84%E7%BC%BA%E7%82%B9"><span class="toc-text"> 非聚集索引的缺点</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A6%86%E7%9B%96%E7%B4%A2%E5%BC%95"><span class="toc-text"> 覆盖索引</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#26%E6%9C%80%E5%B7%A6%E5%89%8D%E7%BC%80%E5%8E%9F%E5%88%99"><span class="toc-text"> 2.6最左前缀原则</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#27%E5%A6%82%E4%BD%95%E4%B8%BA%E8%A1%A8%E5%AD%97%E6%AE%B5%E6%B7%BB%E5%8A%A0%E7%B4%A2%E5%BC%95"><span class="toc-text"> 2.7如何为表字段添加索引</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/post/a647efeab291/" title="【gal评】-交响乐之雨"><img src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/synphonic_haku.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【gal评】-交响乐之雨"/></a><div class="content"><a class="title" href="/post/a647efeab291/" title="【gal评】-交响乐之雨">【gal评】-交响乐之雨</a><time datetime="2021-10-29T01:10:58.000Z" title="发表于 2021-10-29 09:10:58">2021-10-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/post/858ff2ba3ad9/" title="当我们在玩游戏时，我们在玩什么"><img src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/genshin.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="当我们在玩游戏时，我们在玩什么"/></a><div class="content"><a class="title" href="/post/858ff2ba3ad9/" title="当我们在玩游戏时，我们在玩什么">当我们在玩游戏时，我们在玩什么</a><time datetime="2021-05-19T15:37:10.000Z" title="发表于 2021-05-19 23:37:10">2021-05-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/post/114244095f3c/" title="你好，Hexo"><img src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/nier.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="你好，Hexo"/></a><div class="content"><a class="title" href="/post/114244095f3c/" title="你好，Hexo">你好，Hexo</a><time datetime="2021-04-16T09:21:58.000Z" title="发表于 2021-04-16 17:21:58">2021-04-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/post/709e1cd6d598/" title="日本语之森-N1语法（一）"><img src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/dog_food.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="日本语之森-N1语法（一）"/></a><div class="content"><a class="title" href="/post/709e1cd6d598/" title="日本语之森-N1语法（一）">日本语之森-N1语法（一）</a><time datetime="2021-04-16T04:29:17.000Z" title="发表于 2021-04-16 12:29:17">2021-04-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/post/8cecd96a62b8/" title="《标准日语语法》学习笔记——第一章绪论"><img src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/86695978_p0.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="《标准日语语法》学习笔记——第一章绪论"/></a><div class="content"><a class="title" href="/post/8cecd96a62b8/" title="《标准日语语法》学习笔记——第一章绪论">《标准日语语法》学习笔记——第一章绪论</a><time datetime="2021-01-03T23:18:59.000Z" title="发表于 2021-01-04 07:18:59">2021-01-04</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2021 - 2022 By 叶町</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><span>CDN BY <a target="_blank" rel="noopener" href="https://www.jsdelivr.com/">jsdelivr</a></span><br><div  style="display:flex;justify-content:center;align-items:center"><span>本网站由 </span><a href=https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral><img height="30" src= "/image/loading.gif" data-lazy-src="https://testingcf.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/upyun_logo.png" alt="又拍云"></a><span>提供CDN加速</span></div></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page@5/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu@4/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>(()=>{
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'hello-cloudbase-4g4zs9fdc78abf63',
      region: '',
      onCommentLoaded: function () {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)'))
      }
    }, null))
  }

  const getCount = () => {
    const countELement = document.getElementById('twikoo-count')
    if(!countELement) return
    twikoo.getCommentsCount({
      envId: 'hello-cloudbase-4g4zs9fdc78abf63',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      countELement.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const runFn = () => {
    init()
    
  }

  const loadTwikoo = () => {
    if (typeof twikoo === 'object') {
      setTimeout(runFn,0)
      return
    } 
    getScript('https://cdn.jsdelivr.net/npm/twikoo@1/dist/twikoo.all.min.js').then(runFn)
  }

  if ('Twikoo' === 'Twikoo' || !false) {
    if (false) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script>window.addEventListener('load', () => {
  const changeContent = (content) => {
    if (content === '') return content

    content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[图片]') // replace image link
    content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[链接]') // replace url
    content = content.replace(/<pre><code>.*?<\/pre>/gi, '[代码]') // replace code
    content = content.replace(/<[^>]+>/g,"") // remove html tag

    if (content.length > 150) {
      content = content.substring(0,150) + '...'
    }
    return content
  }

  const getComment = () => {
    const runTwikoo = () => {
      twikoo.getRecentComments({
        envId: 'hello-cloudbase-4g4zs9fdc78abf63',
        region: '',
        pageSize: 6,
        includeReply: true
      }).then(function (res) {
        const twikooArray = res.map(e => {
          return {
            'content': changeContent(e.comment),
            'avatar': e.avatar,
            'nick': e.nick,
            'url': e.url + '#' + e.id,
            'date': new Date(e.created).toISOString()
          }
        })

        saveToLocal.set('twikoo-newest-comments', JSON.stringify(twikooArray), 10/(60*24))
        generateHtml(twikooArray)
      }).catch(function (err) {
        const $dom = document.querySelector('#card-newest-comments .aside-list')
        $dom.innerHTML= "无法获取评论，请确认相关配置是否正确"
      })
    }

    if (typeof twikoo === 'object') {
      runTwikoo()
    } else {
      getScript('https://cdn.jsdelivr.net/npm/twikoo@1/dist/twikoo.all.min.js').then(runTwikoo)
    }
  }

  const generateHtml = array => {
    let result = ''

    if (array.length) {
      for (let i = 0; i < array.length; i++) {
        result += '<div class=\'aside-list-item\'>'

        if (false) {
          const name = 'data-lazy-src'
          result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'></a>`
        }
        
        result += `<div class='content'>
        <a class='comment' href='${array[i].url}' title='${array[i].content}'>${array[i].content}</a>
        <div class='name'><span>${array[i].nick} / </span><time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time></div>
        </div></div>`
      }
    } else {
      result += '没有评论'
    }

    let $dom = document.querySelector('#card-newest-comments .aside-list')
    $dom.innerHTML= result
    window.lazyLoadInstance && window.lazyLoadInstance.update()
    window.pjax && window.pjax.refresh($dom)
  }

  const newestCommentInit = () => {
    if (document.querySelector('#card-newest-comments .aside-list')) {
      const data = saveToLocal.get('twikoo-newest-comments')
      if (data) {
        generateHtml(JSON.parse(data))
      } else {
        getComment()
      }
    }
  }

  newestCommentInit()
  document.addEventListener('pjax:complete', newestCommentInit)
})</script><script src="https://testingcf.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/autoload.js"></script><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>